package com.boatAnchorAssistant.service.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boatAnchorAssistant.pojo.dto.authorization.GetAuthorizedByTargetIdDto;
import com.boatAnchorAssistant.pojo.dto.authorization.ResourceAuthorizationDto;
import com.boatAnchorAssistant.pojo.entity.Authorization;
import com.boatAnchorAssistant.pojo.enums.authorized.AuthorizedTypeEnum;
import com.boatAnchorAssistant.service.mapper.AuthorizationMapper;
import com.boatAnchorAssistant.service.repository.in.AuthorizationRepository;
import com.boatAnchorAssistant.service.utils.StringUtil;
import nirvana.core.repository.Repository;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【描 述】：
 * 【环 境】：J2SE
 * 【详 细】：
 *
 */
@Service
public class AuthorizationRepositoryImpl extends Repository<AuthorizationMapper, Authorization> implements AuthorizationRepository {

    private static final String AUTHORIZATION_KEY = "AUTHORIZATION_";

    private final AuthorizationMapper mapper;

    private final RedisTemplate<String, Integer> integerRedisTemplate;


    public AuthorizationRepositoryImpl(AuthorizationMapper mapper, RedisTemplate<String, Integer> integerRedisTemplate) {
        this.mapper = mapper;
        this.integerRedisTemplate = integerRedisTemplate;
    }


    public String getAuthorizationKey(Long targetId) {
        String key = StringUtil.jointString(AUTHORIZATION_KEY, targetId.toString());
        return key;
    }

    /**
     * 获取对象的可用资源汇总
     *
     * @param targetIds
     * @return
     */
    @Override
    public List<Long> getAvailableResourceByTargetIds(List<Long> targetIds) {
        if (CollectionUtils.isEmpty(targetIds)) {
            return Collections.EMPTY_LIST;
        }
        return mapper.getAvailableResourceByTargetIds(targetIds);
    }

    /**
     * 拼接授权key
     * @param dto
     * @return
     */
    public String getAuthorizedMapKey(GetAuthorizedByTargetIdDto dto) {
        Long targetId = dto.getTargetId();
        AuthorizedTypeEnum authorizedType = dto.getAuthorizedType();
        String key = "AuthorizedMapKey" + authorizedType.getId() + targetId;
        return key;
    }


    /**
     * 清空授权
     *
     * @param targetId
     * @param type
     */
    @Override
    public void clear(Long targetId, AuthorizedTypeEnum type) {
        if (targetId==null||type==null){
            return;
        }

        GetAuthorizedByTargetIdDto dto = new GetAuthorizedByTargetIdDto();
        dto.setTargetId(targetId);
        dto.setAuthorizedType(type);
        String authorizedMapKey = getAuthorizedMapKey(dto);

        QueryWrapper<Authorization> wrapper = getWrapper();
        wrapper.eq("authorized_value", type);
        wrapper.eq("target_id",targetId);
        remove(wrapper);

        //清理缓存
        integerRedisTemplate.delete(authorizedMapKey);
    }

    /**
     * 获取对象的授权map
     *
     * @param dto
     * @return
     */
    @Override
    public Map<Long, Integer> getAuthorizedMap(GetAuthorizedByTargetIdDto dto) {
        String authorizedMapKey = getAuthorizedMapKey(dto);
        HashOperations<String, String, Integer> hash = integerRedisTemplate.opsForHash();
        Map<String, Integer> map = hash.entries(authorizedMapKey);
        if (CollectionUtils.isEmpty(map)) {
            List<ResourceAuthorizationDto> authorizedByTargetId = mapper.getAuthorizedByTargetId(dto);
            map = authorizedByTargetId
                    .stream()
                    .collect(Collectors.toMap(d-> d.getResourceId().toString(), ResourceAuthorizationDto::getAuthorizedValue));
            hash.putAll(authorizedMapKey,map);
        }
        Map<Long, Integer> authMap = map.entrySet()
                .stream()
                .collect(Collectors.toMap(
                        e -> {
                            return Long.valueOf(e.getKey());
                        },
                        e -> e.getValue()

                ));
        return authMap;
    }

    /**
     * 批量移除授权
     *
     * @param targetIds
     */
    @Override
    public void bathRemoveTargetAuthorized(List<Long> targetIds) {
        if (CollectionUtils.isEmpty(targetIds)) {
            return;
        }
        //拼接key
        ArrayList<String> keys = new ArrayList<>();
        for (Long targetId : targetIds) {
            String key = getAuthorizationKey(targetId);
            keys.add(key);
        }

        integerRedisTemplate.delete(keys);
        mapper.bathRemoveTargetAuthorized(targetIds);
    }

    /**
     * 获取权限
     *
     * @param dto
     * @return
     */
    @Override
    public List<Long> getTargetAuthorizedList(GetAuthorizedByTargetIdDto dto) {
        String authorizedMapKey = getAuthorizedMapKey(dto);
        HashOperations<String, Long, Integer> hash = integerRedisTemplate.opsForHash();
        Map<Long, Integer> map = hash.entries(authorizedMapKey);
        List<Long> list = map.keySet().stream().collect(Collectors.toList());

        return list;
    }
}